package com.adee.secure;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 对称加密 DES
 */
public class Test003_DES {
    public static final String DES = "DES";
    public static void main(String[] args) throws Exception{
        String key = "1234567890qwertyuiopasdfghjklzxcvbnm"; // 密码
        String txt = "hello moto 嘎嘎嘎！！！啦啦啦。。。"; // 明文
        byte[] encrypt = encrypt(txt.getBytes(), key.getBytes("UTF-8"));
        System.out.println("明文：" + txt);
        System.out.println("加密：" + Base64.getEncoder().encodeToString(encrypt));
        byte[] decrypt = decrypt(encrypt, key.getBytes("UTF-8"));
        System.out.println("解密：" + new String(decrypt, "UTF-8"));
    }

    //DES加密
    public static byte[] encrypt(byte[] bytes, byte[] key) throws Exception{
        //key
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(dks);
        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        //用密匙初始化Cipher对象,ENCRYPT_MODE用于将 Cipher 初始化为加密模式的常量
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
        //现在，获取数据并加密，正式执行加密操作
        return cipher.doFinal(bytes); //按单部分操作加密或解密数据，或者结束一个多部分操作
    }

    //DES解密
    public static byte[] decrypt(byte[] bytes, byte[] key) throws Exception{
        //key
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(dks);
        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        //用密匙初始化Cipher对象,ENCRYPT_MODE用于将 Cipher 初始化为加密模式的常量
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
        //现在，获取数据并加密，正式执行加密操作
        return cipher.doFinal(bytes); //按单部分操作加密或解密数据，或者结束一个多部分操作
    }
}
